const router = require('express').Router();
const { check, validationResult } = require('express-validator'); //数据验证
const passport = require("../modules/passport");
const loginControllers = require("../controllers/loginControllers");
/* GET */
router.post(
  '/',
  [
    check('username').notEmpty().withMessage('用户名不能为空！'),
    check('password').notEmpty().withMessage('密码不能为空！'),
    check('usertype').notEmpty().withMessage('账号类型不能为空')
      .isIn(["1","2","3"]).withMessage('账号类型不正确')
  ],
  async function (req, res, next) {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
      return res.sendResult(null, 400, errors.array()[0].msg);
    }
    let data = null;
    if (req.body.usertype == 1) {
      data = await loginControllers.mangerLogin( req.body.username,req.body.password );
    } else if (req.body.usertype == 2) {
      data = await loginControllers.teacherLogin( req.body.username,req.body.password );
    } else {
      data = await loginControllers.studentLogin( req.body.username,req.body.password );
    }
    if(data){
      let token = passport.authenticate(data);
      data.usertype = req.body.usertype;
      res.sendResult({
        user:data,
        token
      },200,"登录成功");
    }else{
      res.sendResult(data===undefined&&null,400,"用户名或密码错误");
    }
  });


module.exports = router;
